﻿using System;
using System.Windows.Forms;
using AutoUpdater;
using System.Net;
using System.Xml;
using System.IO;

namespace YYY
{
    public partial class UpdateForm : Form
    {
        public UpdateForm()
        {
            InitializeComponent();
            //  InitCheckUpdateini();
            InitTarget();
            InitCheckUpdate();
        }
        /*
        void InitCheckUpdateini()
        {
           
            try
            {
                string v = versionFilesop.getappvesion();
                if (string.IsNullOrWhiteSpace(v))
                {
                    MessageBox.Show("检测不到当前的版本信息!");
                    OperProcess op = new OperProcess();
                    op.StartProcess();
                    return;
                }
                string refile = versionFilesop.getapprefileurl();
                if (string.IsNullOrWhiteSpace(refile))
                {
                    MessageBox.Show("远程更新版本文件地址不存在！");
                    OperProcess op = new OperProcess();
                    op.StartProcess();
                    return;
                }

                Dictionary<string, versionFiles> listvRemotFile = new KnightsWarriorAutoupdater.AutoUpdater().ParsevRemoteXml(refile);
                versionFiles Enabled = listvRemotFile["Enabled"];
                if (!Convert.ToBoolean(Enabled.V))
                {
                    MessageBox.Show("远程更新没有开启！");
                    OperProcess op = new OperProcess();
                    op.StartProcess();
                    return;
                }

                versionFiles newv = listvRemotFile["newv"];
                versionFiles lastv = listvRemotFile["lastv"];
                if (Convert.ToDouble(lastv.V) > Convert.ToDouble(v))
                {
                    //强制更新
                    MessageBoxButtons messButton = MessageBoxButtons.OKCancel;
                    DialogResult dr = MessageBox.Show("当前版本太旧了,是否立即更新?", "提示信息", messButton);
                    if (dr == DialogResult.OK)//如果点击“确定”按钮
                    {
                        return;
                    }
                    else
                    {
                        System.Environment.Exit(0);
                    }

                }
                if (Convert.ToDouble(newv.V) > Convert.ToDouble(v))
                {
                    //选择更新
                    MessageBoxButtons messButton = MessageBoxButtons.OKCancel;
                    DialogResult dr = MessageBox.Show("有新的版本,是否需要更新?", "提示信息", messButton);
                    if (dr == DialogResult.OK)//如果点击“确定”按钮
                    {
                        return;
                    }
                    else
                    {
                       
                         
                            OperProcess op = new OperProcess();
                            op.StartProcess();
                            return;
                      
                    }
                }
                //else
                //{
                //    OperProcess op = new OperProcess();
                //    op.StartProcess();
                //    return;
                //}
            }
            catch (Exception ex)
            {
                NLogger.Error(ex.ToString());
                MessageBox.Show(ex.Message);
                System.Environment.Exit(0);
            }
        }
        */

            /// <summary>
            /// 获取目标程序
            /// </summary>
        void InitTarget() {
            
            this.Text = AppConfig.GetConfigValue("AppTitle");
            string targetName = AppConfig.GetConfigValue("AppName");
            if (string.IsNullOrEmpty(targetName))
            {
                targetName = "AppYYY.dll";
                AppConfig.SetConfigValue("AppName", targetName);
            }
            ConstFile.IsDll = Path.GetExtension(targetName).ToLower() == ".dll";
            ConstFile.MainExeName = Path.GetFileNameWithoutExtension(targetName);
            if (ConstFile.IsDll) {
                ConstFile.DllAppName = AppConfig.GetConfigValue("StartClass");
            }
        }
        void InitCheckUpdate()
        {
          
            #region check and download new version program
            bool bHasError = false;
            IAutoUpdater autoUpdater = new AutoUpdater.AutoUpdater();
            try
            {
               autoUpdater.Update();
            }
            catch (WebException exp)
            {
                MessageBox.Show("服务器连接失败:"+exp.Message);
                bHasError = true;
            }
            catch (XmlException exp)
            {
                bHasError = true;
                MessageBox.Show("下载更新文件错误:" + exp.Message);
            }
            catch (NotSupportedException exp)
            {
                bHasError = true;
                MessageBox.Show("升级文件配置错误:" + exp.Message);
            }
            catch (ArgumentException exp)
            {
                bHasError = true;
                MessageBox.Show("下载升级文件错误:" + exp.Message);
            }
            catch (Exception exp)
            {
                bHasError = true;
                MessageBox.Show("更新过程中出现错误:" + exp.Message);
            }
            finally
            {


                if (bHasError == true)
                {
                    try
                    {
                 //  MessageBox.Show("111");
                    autoUpdater.RollBack();
                    }
                    catch (Exception)
                    {
                        //Logger.Error(ex.ToString());
                        //Log the message to your file or database
                    }
                }



                //XmlDocument xmlDoc = new XmlDocument();

                //string s = System.Windows.Forms.Application.StartupPath + "/.exe.config";

                //xmlDoc.Load(s);

                //XmlNode node = xmlDoc.SelectSingleNode("//appSettings");

                //XmlElement element = (XmlElement)node.SelectSingleNode(@"//add [@key=""vesion""]");

                //if (element != null)

                //{

                //    element.SetAttribute("value", "2.0");

                //}

                //xmlDoc.Save(s);

                //xmlDoc = null;

                //this.Close();

                
                //启动进程
            }
            #endregion
        }

        private void UpdateForm_Load(object sender, EventArgs e)
        {
            if (ConstFile.IsDll)
            {
                this.Hide();
                OperProcess.StartFromDll(ConstFile.MainExeName, ConstFile.DllAppName);
                this.Close();
            }
            else
            {
                OperProcess.StartExe(ConstFile.MainExeName);
                OperProcess.ExitProgame(ConstFile.ThisName);
            }
        }
    }
}
